using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Magiq.Insert {
    public class EnumerableInsert<TFrom, TNew> : IInsert  {
        
        private readonly Expression<Func<TFrom, TNew>> newExpression;

        private readonly IEnumerable<TFrom> where;

        public EnumerableInsert(IEnumerable<TFrom> where, Expression<Func<TFrom, TNew>> newValueExpression) {
            this.where = where;
            newExpression = newValueExpression;
        }

        #region IEnumerableInsert<TNew> Members

        public int Into<TDestination>(IEnumerable<TDestination> destination) where TDestination : class {
            if (!typeof(TDestination).IsAssignableFrom(typeof(TNew)))
                throw new InvalidOperationException("Type " + typeof(TNew).FullName + " should inherit from " +
                                                    typeof(TDestination).FullName);

            var collection = Magiq.For(destination).ItemAdderFor<TNew,TDestination>(destination);

            var @new = newExpression.Compile();
            var items = where.ToArray();
            collection.Add(items.Select(@new));

            return items.Length;
        }

        #endregion
    }
}